package sendGoodsRecord

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/purchase/internal/svc"
	"insighttracking/apps/purchase/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CreateSendGoodsRecordApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCreateSendGoodsRecordApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CreateSendGoodsRecordApiLogic {
	hostname, _ := os.Hostname()
	return &CreateSendGoodsRecordApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CreateSendGoodsRecordApiLogic) CreateSendGoodsRecordApi(req *types.CreateSendGoodsRecordReq) (resp string, err error) {
	// 创建发货数据
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	for _, item := range req.IdList {
		if err = service.OrdersService.ModifyStatusByIdApi(l.ctx, tx, []int64{item}, enum.OrdersAlreadyShippedEnum); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("操作失败")
		}
		if err = service.OrdersDetailService.ModifyStatusByOrderIdListApi(l.ctx, tx, item, enum.OrdersAlreadyShippedEnum); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("操作失败")
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("操作失败")
	}
	return "操作成功", nil
}
